package com.lagou.springbootframework;

import com.lagou.springbootframework.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * Spring官方文档中给出了基于Servlet3.0规范如何使用Java代码实现web.xml配置的example
 * MyWebApplicationInitializer就相当于传统mvc开发中的web.xml
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("初始化 MyWebApplicationInitializer");
        //web配置的上下文
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        //把AppConfig注册进来，而AppConfig做的事情就是开启包扫描
        ac.register(AppConfig.class);
        ac.refresh();

        //创建servlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        //注册区域,添加拦截路径
        ServletRegistration.Dynamic registration = servletContext.addServlet("/",servlet);
        //下面的就是web.xml中的<load-on-startup>1</load-on-startup>
        //它的值必须是一个整数，表示servlet应该被载入的顺序,当值为0或者大于0时，表示容器在应用启动时就加载并初始化这个servlet
        //当值小于0或者没有指定时，则表示容器在该servlet被选择时才会去加载
        registration.setLoadOnStartup(1);
        registration.addMapping("/");


    }
}
